from selenium import webdriver
import time
import unittest
from functools import wraps
import configparser
import os
from framework.logger import Logger


# 开始结束SetupTeardown
class SetupTeardown(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        print("class module 开始测试>>>>>>>>>>>")

    @classmethod
    def tearDownClass(cls):
        print("class module 测试结束>>>>>>>>>>>>\n")

    def setUp(self):
        print("setup begin test")

    def tearDown(self):
        print("teardown test end!")


# 打开浏览器
class Browser:
    """浏览器相关操作"""
    def __init__(self):
        # self.browser_driver = webdriver.Firefox()
        self.browser_driver = webdriver.Chrome()

    def open(self, url):
        self.browser_driver.get(url=url)
        self.browser_driver.maximize_window()
        self.browser_driver.implicitly_wait(10)  # 隐式等待时间设定10s
        time.sleep(1)
        return self.browser_driver


# 跳过测试用例的装饰器
def skip_dependon(depend=""):
    """
    :param depend: 依赖的用例函数名，默认为空
    :return: wraper_func
    """

    def wraper_func(test_func):
        @wraps(test_func)  # @wraps：避免被装饰函数自身的信息丢失
        def inner_func(self):
            if depend == test_func.__name__:
                raise ValueError("{} cannot depend on itself".format(depend))
            # print("self._outcome", self._outcome.__dict__)
            # 此方法适用于python3.4 +
            # 如果是低版本的python3，请将self._outcome.result修改为self._outcomeForDoCleanups
            # 如果你是python2版本，请将self._outcome.result修改为self._resultForDoCleanups
            failures = str([fail[0] for fail in self._outcome.result.failures])
            errors = str([error[0] for error in self._outcome.result.errors])
            skipped = str([error[0] for error in self._outcome.result.skipped])
            flag = (depend in failures) or (depend in errors) or (depend in skipped)
            if failures.find(depend) != -1:
                # 输出结果 [<__main__.TestDemo testMethod=test_login>]
                # 如果依赖的用例名在failures中，则判定为失败，以下两种情况同理
                # find()方法：查找子字符串，若找到返回从0开始的下标值，若找不到返回 - 1
                test = unittest.skipIf(flag, "{} failed".format(depend))(test_func)
            elif errors.find(depend) != -1:
                test = unittest.skipIf(flag, "{} error".format(depend))(test_func)
            elif skipped.find(depend) != -1:
                test = unittest.skipIf(flag, "{} skipped".format(depend))(test_func)
            else:
                test = test_func
            return test(self)
        return inner_func
    return wraper_func


# 获取config.ini文件中的配置数据
class Config:

    def __init__(self):
        self.config = configparser.ConfigParser()
        self.path = os.path.dirname(os.path.split(os.path.realpath(__file__))[0]) + '/config/config.ini'

    def get_config(self, section, key=None):
        """
        :param section: section
        :param key: key传了就以字符串格式返回指定key的数据，未传就列表形式返回当前section下的所有数据
        格式如下：[('test_url', 'https://www.kanman.com'), ('account', '15928152911'), ('password', '1234abcd')]
        :return:
        """
        self.config.read(self.path, encoding="utf-8-sig")
        if key:
            return self.config.get(section, key)
        else:
            return self.config.items(section)

# create a logger instance
logger = Logger(logger="BasePage")
con = Config()
browser = Browser()
driver = browser.open(url=con.get_config(section="test_config", key="test_url"))
